package com.jec.protocol;

import lombok.Getter;
import lombok.extern.log4j.Log4j;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Properties;

@Log4j
public class Networks {

    @Getter
    private static String manageHost = getLocalAddress();

    @Getter
    private static int managePort = 3600;

    @Getter
    public static String recordHost = getLocalAddress();

    @Getter
    public static int recordPort = 6001;


    public static void bootstrap(Properties prop) {

        try {

            String temp;

            temp = prop.getProperty("network.manage.host");
            if(temp != null) {
                manageHost = temp;
            }

            temp = prop.getProperty("network.manage.port");
            if(temp != null) {
                managePort = Integer.parseInt(temp);
            }

            temp = prop.getProperty("network.record.host");
            if(temp != null) {
                recordHost = temp;
            }

            temp = prop.getProperty("network.record.port");
            if(temp != null) {
                recordPort = Integer.parseInt(temp);
            }

        } catch(Exception e) {

            log.error("Initial network properties error, please check the config file!");

        }

    }

    private static String getLocalAddress() {

        try {
            Enumeration<NetworkInterface> enitf = NetworkInterface.getNetworkInterfaces();
            while(enitf.hasMoreElements()) {
                NetworkInterface nitf = enitf.nextElement();
                Enumeration<InetAddress> eia = nitf.getInetAddresses();
                while(eia.hasMoreElements()) {
                    InetAddress ia = eia.nextElement();

                    if(ia instanceof Inet4Address) {
                        String address = ia.getHostAddress();
                        if(!address.equals("127.0.0.1"))
                            return address;
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "";
    }

}
